package com.yylending.las.personal.loan;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yylending.las.Global;
import com.yylending.las.R;
import com.yylending.las.base.BaseActivity;
import com.yylending.las.common.utils.FormatUtils;
import com.yylending.las.common.utils.TimeUtils;
import com.yylending.las.StatIDSet;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.webview.WebViewActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 借据
 * Created by ying_he on 2017/6/5.<br>
 * Copyright  2017 www.yylending.com. All Rights Reserved.<br><br>
 */
public class DebtEvidenceActivity extends BaseActivity implements DebtEvidencePresenter.View {
    private static final String TAG = DebtEvidenceActivity.class.getSimpleName();
    private static final String KEY_INTENT_LOAN_NO = "intent_loan_no";
    private static final String KEY_INTENT_LOAN_TYPE = "intent_loan_type";

    private static final int LOADER_ID = 1;

    @BindView(R.id.withdraw_amount_tv)
    TextView mWithdrawAmountTv;
    @BindView(R.id.terminally_repayment_tv)
    TextView mTerminallyRepaymentTv;
    @BindView(R.id.start_end_time_tv)
    TextView mStartEndTimeTv;
    @BindView(R.id.first_repay_date_tv)
    TextView mFirstRepayDateTv;
    @BindView(R.id.month_repay_date_tv)
    TextView mMonthRepayDateTv;
    @BindView(R.id.repay_period_tv)
    TextView mRepayPeriodTv;
    @BindView(R.id.borrowers_name_tv)
    TextView mBorrowersNameTv;
    @BindView(R.id.borrowers_id_card_tv)
    TextView mBorrowersIdCardTv;
    @BindView(R.id.bank_card_tv)
    TextView mBankCardTv;
    @BindView(R.id.check_debt_evidence_rl)
    RelativeLayout mCheckDebtEvidenceRl;
    @BindView(R.id.bank_name_tv)
    TextView mBankNameTv;
    @BindView(R.id.retry_tv)
    TextView mRetryTv;
    @BindView(R.id.retry_image)
    ImageView mRetryImage;
    @BindView(R.id.no_network_layout)
    RelativeLayout mNoNetworkLayout;

    Unbinder mUnbind;

    private DebtEvidencePresenter mPresenter;

    public static void start(Activity aty, String loanNo, String loanType) {
        Intent intent = new Intent(aty, DebtEvidenceActivity.class);
        intent.putExtra(KEY_INTENT_LOAN_NO, loanNo);
        intent.putExtra(KEY_INTENT_LOAN_TYPE, loanType);
        aty.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_debt_evidence);
        mUnbind = ButterKnife.bind(this);
        setTitle(R.string.debt_evidence);
        getSupportLoaderManager().initLoader(LOADER_ID, null, this);
    }

    private void initData(DebtEvidenceModel.debtEvidence debtEvidence) {
        mWithdrawAmountTv.setText(FormatUtils.getDecoratedAmountWithSymbol(debtEvidence.businessSum)); // 借款金额
        mTerminallyRepaymentTv.setText(FormatUtils.getAmountWithSymbol(debtEvidence.monthPay)); // 每期应还
        mStartEndTimeTv.setText(TimeUtils.formatDateTimeSlash(Long.valueOf(debtEvidence.putOutDate)) + " - " + TimeUtils.formatDateTimeSlash(Long.valueOf(debtEvidence.maturityDate))); // 起止时间
        mFirstRepayDateTv.setText(TimeUtils.formatDateTimeSlash(Long.valueOf(debtEvidence.firstRepayDate))); // 首次还款日
        mMonthRepayDateTv.setText(String.format(getString(R.string.each_month_day), debtEvidence.beginDate)); // 每月还款日
        mRepayPeriodTv.setText(String.format(getString(R.string.left_pay_term), debtEvidence.loanTerm)); // 借款期数
        mBorrowersNameTv.setText(debtEvidence.customerName); // 借款人姓名
        mBorrowersIdCardTv.setText(FormatUtils.hiddenPartStr(6, debtEvidence.certId.length() - 4, "*", debtEvidence.certId)); // 借款人身份证

		if(TextUtils.isEmpty(debtEvidence.loanBank)){
			mBankNameTv.setText(R.string.never_bind_bank_card); // 收款账户
		}else{
			mBankNameTv.setText(debtEvidence.loanBank); // 收款账户
			if(!TextUtils.isEmpty(debtEvidence.loanCardId)){
				String bankCardLastFour = "";
				int length = debtEvidence.loanCardId.length();
				if (length > 4) {
					bankCardLastFour = debtEvidence.loanCardId.substring(length - 4, length);
				}
				if (!TextUtils.isEmpty(bankCardLastFour)) {
					mBankCardTv.setText(String.format(getString(R.string.bank_card_last_four_num), bankCardLastFour)); // 银行卡尾号
				}
			}
		}
    }

    @Override
    public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
        mPresenter = (DebtEvidencePresenter) data;
        mPresenter.attach(this);
        Intent intent = getIntent();
        mPresenter.getDebtEvidence(intent.getStringExtra(KEY_INTENT_LOAN_NO), intent.getStringExtra(KEY_INTENT_LOAN_TYPE));
    }

    @Override
    public Loader<Presenter> onCreateLoader(int id, Bundle args) {
        return new PresenterLoader<>(this, new DebtEvidencePresenter.Generator());
    }

    @Override
    public void getDebtEvidenceSuccess(DebtEvidenceModel.debtEvidence debtEvidence) {
        mNoNetworkLayout.setVisibility(View.GONE);
        initData(debtEvidence);
    }

    @Override
    public void getDebtEvidenceFailed(String tips) {
        mNoNetworkLayout.setVisibility(View.VISIBLE);
        showToast(tips);
    }

    @Override
    public void onFunctionalError(Throwable e, boolean autoTips, int functionalCode) {
        super.onFunctionalError(e, autoTips, functionalCode);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mNoNetworkLayout.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getSupportLoaderManager().destroyLoader(LOADER_ID);
        mUnbind.unbind();
    }

    @OnClick({R.id.check_debt_evidence_rl, R.id.no_network_layout})
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){
            case R.id.check_debt_evidence_rl:
				StatService.onEventWithSingleAttribute(this, StatIDSet.EVENT_ID_CHECK_LOAN_CONTRACT,getIntent().getStringExtra(KEY_INTENT_LOAN_TYPE));
				if (!TextUtils.isEmpty(Global.DEBT_DOCUMENT_URL)) {
                    WebViewActivity.start(this, Global.BASE_URL + Global.DEBT_DOCUMENT_URL, getString(R.string.debt_contract), -1);
                }
                break;
            case R.id.no_network_layout:
                Intent intent = getIntent();
                mPresenter.getDebtEvidence(intent.getStringExtra(KEY_INTENT_LOAN_NO), intent.getStringExtra(KEY_INTENT_LOAN_TYPE));
                break;
            default:
                break;
        }
    }
}
